<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm @submit="getList" @reset="reset">
        <el-form-item>
          <label id="select_nation" for="top_selectList">标签类型：</label>
            <basSelects
              ref="select_modelData"
              v-model:modelData="modelData"
              placeholder="请输入后搜索"
              :option="this.options"
              @getOption="changeModelData"
              fit-input-width>
            </basSelects>
        </el-form-item>
      </AppSearchForm>
      <div class="btn-area">
        <el-button @click="openDialog" type="primary"> 新增 </el-button>
        <el-button @click="exportFile" type="primary"> EXCEL导出 </el-button>
        <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        @change="getList()"
        :autostyle="'height: calc(100% - 80px);'"
        :option="tableData.option"
      >
        <el-table-column
          show-overflow-tooltip
          type="selection"
          width="55"
          fixed="left"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="titleType"
          width="100"
          label="标签类型"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="name"
          width="150"
          label="名称"
        />

        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click.stop="update(scope.row)" type="primary"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
      <el-dialog
        :title="dialogData.title"
        v-model="dialogData.show"
        width="500px"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          label-width="80px"
          ref="form"
        >
          <el-form-item prop="titleType" label="标签类型">
            <basSelects
              v-model="formData.titleType"
              :placeholder="请输入后搜索"
              :option="this.options"
              @getOption="changeTitleType"
              fit-input-width>
            </basSelects>
          </el-form-item>
          <el-form-item prop="name" label="名称">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel" link>取消</el-button>
            <el-button type="primary" @click="submit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import basSelects from "./components/basSelects.vue"
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppTitleBox from "@/components/AppTitleBox.vue";
import { fileDownload } from "@/public/publicUtils";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  components: {
    AppSearchForm,
    AppPageTable,
    AppTitleBox,
    basSelects
  },
  emits: ["update:modelData"],
  data() {
    return {
      query: {
        KeyWords: "",
      },
      loading: false,
      tableData: {
        data: [],
        option: useTableOption(),
      },
      dialogData: {
        show: false,
        title: "",
        btnLoading: false,
      },
      formData: {
        id: 0,
        titleType: "",
        name: "",
        value: 0    // 标签转换value
      },
      companyLabel: [],//企业标签类型
      topCompanyName: '',
      formRules: {
        titleType: [
          { required: true, message: "请输入标签类型", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      options: [],
      modelData: ''
    };
  },
  methods: {
    async getList() {
      this.tableData.option.loading = true;

      let res = await this.$http.get("/api/dict/query", {
        PageIndex: this.tableData.option.page,
        PageSize: this.tableData.option.pageSize,
        keyWords: '企业标签'
      })
      this.options = res.content[0].dictDetails;

      this.$http.get("/api/base/companyTitle/query", {
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize,
          TitleType: this.modelData==""?"":this.translate(this.options,this.modelData).toString()
        }).then((res) => {
          console.log(res);
          this.tableData.data = res.content.map(item=>{
              for(let i = 0;i<this.options.length;i++) {
                  if (item.titleType==this.options[i].value) {
                      item.titleType=this.options[i].label
                  }
              }
              return item
          })
          this.tableData.option.total = res.totalElements
        }).finally(() => {
          this.tableData.option.loading = false;
        });
    },
    changeModelData(data) {
      this.modelData = data 
    },
    changeTitleType(data) {
      this.formData.titleType = data
    },
    reset() {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 15;
      this.$refs.select_modelData.clearModelData()
      this.getList();
    },
    update(data) {
      console.log('this.data',data);
      this.formData = JSON.parse(JSON.stringify(data));
      this.dialogData.title = "编辑企业标签";
      this.dialogData.show = true;
    },
    deleteData(data) {
      this.$http.post("/api/base/companyTitle/delete", {
          idArray: [data.id],
        })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.getList();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    translate(arr,label) {
        for(let i = 0;i<arr.length;i++) {
            if (arr[i].label==label) {
                return arr[i].value
            }
        }
    },
    async submit() {
      this.dialogData.btnLoading = true;
      await this.$refs.form.validate();
      if (this.formData.id) {
        this.$http.post("/api/base/companyTitle/edit", {id:this.formData.id,titleType: this.translate(this.options,this.formData.titleType).toString(), name: this.formData.name})
          .then((res) => {
            if (res.status) {
              this.$message.success(res.message);
              this.getList();
              this.dialogData.show = false;
            } else {
              this.$message.error(res.message);
            }
            this.dialogData.btnLoading = false;
          });
      } else {
        this.$http
          .post("/api/base/companyTitle/create", {titleType: this.translate(this.options,this.formData.titleType).toString(),name: this.formData.name})
          .then((res) => {
            if (res.status) {
              this.$message.success(res.message);
              this.getList();
              this.dialogData.show = false;
            } else {
              this.$message.error(res.message);
            }
            this.dialogData.btnLoading = false;
          });
      }
    },
    cancel() {
      this.dialogData.show = false;
    },
    openDialog() {
      this.formData.titleType = ""
      this.formData.name = ""
      this.dialogData.title = "新增企业标签";
      this.dialogData.show = true;
    },
    exportFile() {
      this.query.keyWords = "download"
      fileDownload("/api/base/companyTitle/download",{TitleType: this.modelData==""?"":this.translate(this.options,this.modelData).toString()}, "企业标签")
        .then(() => {})
        .catch((err) => {
          ElMessage.warning("文件导出失败");
        });
    },
    // 查询所有企业标签
    async getOptions() {
      let res = await this.$http.get("/api/dict/query", {
        PageIndex: this.tableData.option.page,
        PageSize: this.tableData.option.pageSize,
        keyWords: '企业标签'
      })
      this.options = res.content[0].dictDetails;
    },
    /**
     * 多项删除业务
     */
    deleteSelectData() {
      let deleteSelectArray = [];
      this.tableData.option.selected.forEach((t) =>
        deleteSelectArray.push(t.id)
      );
      ElMessageBox.confirm("确定删除所选城市信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$http
            .post("/api/base/companyTitle/delete", {
              idArray: deleteSelectArray,
            })
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message);
                this.getList();
              } else {
                this.$message.error(res.message);
              }
            });
        }).catch(() => {
          this.$message.info("取消删除");
        });
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.formData = {
          nationCode: "",
          nationName: "",
          nationEnName: "",
          customCode: "",
        };
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      }
    },
  },
  created() {
    this.getList();
  },
});
</script>

<style lang="scss" scoped>
.btn-area {
  margin-bottom: 8px;
}
::v-deep .el-select {
  width: 100% !important;
}
.form .el-select--small {
  width: 140px !important;
}
</style>
